package com.ganzi.ganziserver.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 异步任务
 * */
@Configuration
@EnableAsync
public class ExecutorConfig {
    private static Logger log = LoggerFactory.getLogger(ExecutorConfig.class);


    @Value("${threadPool.corePoolSize}")
    private  int corePoolSize;
    @Value("${threadPool.maxPoolSize}")
    private  int maxPoolSize;
    @Value("${threadPool.keepAliveTime}")
    private  int keepAliveTime;
    @Value("${threadPool.queueCapacity}")
    private  int queueCapacity;
    @Value("${threadPool.threadNamePrefix}")
    private  String threadNamePrefix;

    @Bean("taskExecutor")
    public Executor asyncServiceExecutor() {
        log.info("start asyncServiceExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setKeepAliveSeconds(keepAliveTime);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
